package com.hiyee.platform.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hiyee.platform.config.AmapProperties;
import com.hiyee.platform.pojo.bo.LieYingServiceListBO;
import com.hiyee.platform.pojo.bo.LieYingServiceUpdateBO;
import com.hiyee.platform.pojo.bo.LieYingTerminalListBO;
import com.hiyee.platform.pojo.bo.LieYingTerminalUpdateBO;
import com.hiyee.platform.response.ResponseJsonResult;
import com.hiyee.platform.response.ResponseStatusEnum;
import com.hiyee.platform.service.LieYingService;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 猎鹰定位终端控制器
 *
 * @author WangBin
 * @date 2021-11-08
 */
@RestController
@RequestMapping("/lieying")
public class LieYingTerminalController extends BaseController {

    @Autowired
    AmapProperties amapProperties;
    @Autowired
    LieYingService lieYingService;

    @PostMapping("/terminal/add")
    public ResponseJsonResult add(@RequestBody @Valid LieYingTerminalUpdateBO bo, BindingResult bindingResult) throws Exception {
        // 参数校验
        if(bindingResult.hasErrors()) {
            return ResponseJsonResult.error(this.getError(bindingResult));
        }
        // 请求高德接口
        OkHttpClient okHttpClient = new OkHttpClient();
        String requestData = "key=" + amapProperties.getWebKey() + "&sid=" + bo.getSid() + "&name=" + bo.getName() + "&desc=" + bo.getDesc();
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf8"), requestData);
        Request request = new Request.Builder().url(amapProperties.getLieYingTerminalAddUrl()).post(requestBody).build();
        Response response = okHttpClient.newCall(request).execute();
        ObjectMapper objectMapper = new ObjectMapper();
        // 返回数据
        String responseStr = response.body().string();
        JsonNode responseNode = objectMapper.readTree(responseStr);
        System.out.println(responseStr);
        // 接口返回状态码
        String errCode = responseNode.get("errcode").asText();
        if(!errCode.equals("10000")) {
            return ResponseJsonResult.error(responseNode.get("errdetail").asText());
        }
        int tid = Integer.parseInt(responseNode.get("data").get("tid").asText());
        bo.setTid(tid);
        // 保存服务
        lieYingService.insertTerminal(bo);
        return ResponseJsonResult.success();
    }

    @GetMapping("/terminal/list")
    public ResponseJsonResult getList(LieYingTerminalListBO bo, BindingResult bindingResult) {
        // 参数校验
        if(bindingResult.hasErrors()) {
            return ResponseJsonResult.error(this.getError(bindingResult));
        }
        return ResponseJsonResult.success(lieYingService.getTerminalList(bo));
    }

    @PostMapping("/terminal/delete")
    public ResponseJsonResult delete(Integer sid, Integer tid) throws Exception{
        if (tid == null || sid == null) {
            return ResponseJsonResult.error(ResponseStatusEnum.PARAM_ERROR);
        }
        // 删除高德端的终端
        OkHttpClient okHttpClient = new OkHttpClient();
        String requestData = "key=" + amapProperties.getWebKey() + "&sid=" + sid + "&tid=" + tid;
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf8"), requestData);
        Request request = new Request.Builder().url(amapProperties.getLieYingTerminalDeleteUrl()).post(requestBody).build();
        Response response = okHttpClient.newCall(request).execute();
        lieYingService.deleteTerminal(tid);
        return ResponseJsonResult.success();
    }

    @PostMapping("/terminal/update")
    public ResponseJsonResult update(@RequestBody @Valid LieYingServiceUpdateBO bo, BindingResult bindingResult) throws Exception {
        // 参数校验
        if(bindingResult.hasErrors()) {
            return ResponseJsonResult.error(this.getError(bindingResult));
        }
        if(bo.getSid() == null) {
            return ResponseJsonResult.error(ResponseStatusEnum.LIEYING_SERVICE_SID_ERROR);
        }
        // 更新高德端的服务
        OkHttpClient okHttpClient = new OkHttpClient();
        String requestData = "key=" + amapProperties.getWebKey() + "&sid=" + bo.getSid() + "&name=" + bo.getName() + "&desc=" + bo.getDesc();
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=utf8"), requestData);
        Request request = new Request.Builder().url(amapProperties.getLieYingServiceDeleteUrl()).post(requestBody).build();
        Response response = okHttpClient.newCall(request).execute();
        String responseStr = response.body().string();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode responseNode = objectMapper.readTree(responseStr);
        // 接口返回状态码
        String errCode = responseNode.get("errcode").asText();
        if(!errCode.equals("10000")) {
            return ResponseJsonResult.error(responseNode.get("errdetail").asText());
        }
        lieYingService.update(bo);
        return ResponseJsonResult.success();
    }
}
